<?php

namespace App\Controller\Home;

use App\Controller\Example\PoolExample;
use App\Controller\Example\SettlementExample;
use App\Controller\Example\ShopGoodsExample;
use App\Controller\Example\ShopGoodsOrderExample;
use App\Controller\Example\ShopGoodsSkuExample;
use App\Controller\Example\UserAddrExample;
use App\Controller\Example\UserExample;
use App\Models\ConfigModel;
use App\Models\Conn;
use App\Models\PoolModel;
use App\Models\SettlementModel;
use App\Models\ShopGoodsModel;
use App\Models\ShopGoodsOrderModel;
use App\Models\ShopGoodsSkuModel;
use App\Models\UsersAddrModel;
use App\Models\UsersModel;
use Config\Config;
use Core\Common\Common;
use Core\Enums\DigitEnum;
use Core\Enums\ErrorEnum;
use Core\Enums\FundsEnum;
use Core\Result\Result;
use Core\Utils\Utils;

class Caigou
{
    /**
     *  TODO 采购参数
     * @param $data
     * @return void
     */
    public function caiGouInfo($data){
        $assemble = Common::assemble(new UserExample(), $data);
        $conn = new Conn();
        $userInside = UsersModel::getUserInside($conn, $assemble->token);
        $discount = self::getDiscount($conn, $userInside["capping"]);
        $cashback = self::getCashback($conn, $userInside["caigou"]);
        $res["caigouFee"] = ConfigModel::getConfigSingleValName($conn, Config::PROCURE_FEE);
        $res["discount"]=$discount.'';//折扣
        $res["procure"]=$userInside["caigou"];//采购金额
        $res["cashback"]=round($cashback,2);//累计返现
        $res["discountInfo"]["99"] = ConfigModel::getConfigSingleValName($conn, Config::DISCOUNT_99)."折";
        $res["discountInfo"]["999"] = ConfigModel::getConfigSingleValName($conn, Config::DISCOUNT_999)."折";
        $res["discountInfo"]["3999"] = ConfigModel::getConfigSingleValName($conn, Config::DISCOUNT_3999)."折";
        $res["cashbackInfo"]["10000"] =100 * ConfigModel::getConfigSingleValName($conn, Config::CASHBACK_1)."%";
        $res["cashbackInfo"]["20000"] =100 * ConfigModel::getConfigSingleValName($conn, Config::CASHBACK_2)."%";
        $res["cashbackInfo"]["50000"] =100 * ConfigModel::getConfigSingleValName($conn, Config::CASHBACK_5)."%";
        $res["cashbackInfo"]["100000"] =100 * ConfigModel::getConfigSingleValName($conn, Config::CASHBACK_10)."%";
        Result::success($res);
    }

    /**
     * TODO 采购订单余额支付
     * @param $data pay_password address_id sku_id order_number remark
     * @return void
     */
    function caiGouBalanceBuy($data){
        $assemble = Common::assemble(new ShopGoodsOrderExample(), $data);
        $pay_password=$data['pay_password'];
        $address_id=$data['address_id'];
        if($assemble->order_number <= DigitEnum::ZERO){
            Result::error(ErrorEnum::THISORDERHASEXPIRED[$assemble->language]);
        }
        if($address_id <= DigitEnum::ZERO){
            Result::error(ErrorEnum::PLEASESELECTSHIPPINGADDRESS[$assemble->language]);
        }
        if($assemble->sku_id <= DigitEnum::ZERO){
            Result::error(ErrorEnum::ITEMDOESNOTEXIST[$assemble->language]);
        }
        $conn = new Conn();
        $UserPassword = UsersModel::getUserPasswordInside($conn, $assemble->token);
        if($UserPassword["pay_password"] == null){
            Result::error(ErrorEnum::PLEASESETASECONDLEVELPAYMENTPASSWORD[$assemble->language]);
        }
        if($UserPassword["pay_password"] != md5(md5($pay_password))){
            Result::error(ErrorEnum::SECONDLEVELPAYMENTPASSWORDERROR[$assemble->language]);
        }
        $goodsSkuInfo = Common::assemble(new ShopGoodsSkuExample(),ShopGoodsSkuModel::getGoodsSkuInfo($conn, $assemble->sku_id));
        if($goodsSkuInfo->sku_stock < $assemble->order_number){
            Result::error(ErrorEnum::INSUFFICIENTINVENTORY[$assemble->language]);
        }
        $goodsSkuInfo->sku_stock = $goodsSkuInfo->sku_stock - $assemble->order_number;//减去库存
        if($goodsSkuInfo->sku_stock == 0){
            $goodsSkuInfo->sku_stock = '0';
        }
        $ShopGoodsExample = Common::assemble(new ShopGoodsExample(), ShopGoodsModel::getGoodsInfo($conn, $goodsSkuInfo->goods_id));
        if($ShopGoodsExample->is_top == DigitEnum::ZERO || $ShopGoodsExample->is_adopt == DigitEnum::ZERO || $ShopGoodsExample->goods_type != DigitEnum::TWO){
            Result::error(ErrorEnum::ITEMDOESNOTEXIST[$assemble->language]);
        }
        $UserExample = Common::assemble(new UserExample(), UsersModel::getUserInside($conn, $assemble->token));
        $assemble->merchant_id = $ShopGoodsExample->merchant_id;
        $assemble->goods_id = $ShopGoodsExample->goods_id;
        $assemble->order_price = $goodsSkuInfo->sku_sell_price;
        $settlementExample = new SettlementExample();
        $userAddrExample = new UserAddrExample();
        $settlementExample->cost = 0;
        $discount = self::getDiscount($conn, $UserExample->capping);
        $discount = $discount / 10;
        if($discount <= DigitEnum::ZERO || $discount > DigitEnum::ONE) $discount=1;
        $assemble->order_total_price = ($goodsSkuInfo->sku_sell_price * $assemble->order_number) * $discount;
        $userAddrExample->id = $address_id;
        $settlementExample->uid = $assemble->member_id = $userAddrExample->uid = $UserExample->id;
        $assemble->type = $settlementExample->type = DigitEnum::TWO;
        $userAddr = UsersAddrModel::getUserAddr($conn, $userAddrExample);
        if (!$userAddr){
            Result::error(ErrorEnum::DELIVERYADDRESSDOESNOTEXIST[$assemble->language]);
        }
        $balance = $UserExample->money - $assemble->order_total_price;
        if($assemble->order_total_price <= DigitEnum::ZERO || $UserExample->money <= DigitEnum::ZERO || $balance < DigitEnum::ZERO){
            Result::error(ErrorEnum::INSUFFICIENTBALANCE[$assemble->language]);
        }
        $assemble->receipt_name = $userAddr["name"];
        $assemble->receipt_phone = $userAddr["mobile"];
        $assemble->receipt_address = $userAddr["detailed_address"];
        $settlementExample->no = $assemble->order_no = Utils::createOrderNo();
        $shopGoodsExample = new ShopGoodsExample();
        $shopGoodsExample->goods_id = $ShopGoodsExample->goods_id;
        $shopGoodsExample->sales_volume = $ShopGoodsExample->sales_volume + $assemble->order_number;
        $caiGou = $assemble->order_total_price - $goodsSkuInfo->sku_cost_price;
        if($caiGou > 0){
            $settlementExample->money = $caiGou;
        }else{
            $settlementExample->money = 0;
        }
        $conn->shiwuStart();
        $insertSettlementInside = SettlementModel::insertSettlementInside($conn, $settlementExample);
        $SettlementId = $conn->mysql_insert_id();
        $insertShopGoodsOrderInside = ShopGoodsOrderModel::insertShopGoodsOrderInside($conn, $assemble);
        $upShopGoodsSkuInside = ShopGoodsSkuModel::upshopGoodsSkuInside($conn, $goodsSkuInfo);
        $editUserMoneyOutInside = UsersModel::editUserMoneyAndCaiGouInside($conn, $assemble->order_total_price,$UserExample);
        $writeFundsMoney = Funds::writeFundsMoney($conn, $UserExample->id, $assemble->order_no, FundsEnum::PROCURE, -$assemble->order_total_price, $balance, FundsEnum::PROCUREZHCN);
        $upShopGoodsInside = ShopGoodsModel::upShopGoodsInside($conn, $shopGoodsExample);
        if($insertSettlementInside != DigitEnum::ONE || $insertShopGoodsOrderInside != DigitEnum::ONE || $upShopGoodsSkuInside != DigitEnum::ONE || $editUserMoneyOutInside != DigitEnum::ONE || $writeFundsMoney != DigitEnum::ONE || $upShopGoodsInside != DigitEnum::ONE){
            $conn->shiwuRollback();
            Result::error(ErrorEnum::ORDERPLACEMENTFAILED[$assemble->language]);
        }
        $conn->shiwuEnd();
        if($settlementExample->money >0){
            Sett::settlement($UserExample->id,$SettlementId,$settlementExample->money,$settlementExample->no);
        }
        Result::success(ErrorEnum::PAYMENTSUCCESSFUL[$assemble->language]);
    }
    /**
     * TODO 采购返现领取
     *
     * */
    public function collectProcure($data){
        $assemble = Common::assemble(new UserExample(), $data);
        $conn = new Conn();
        $UserExample = Common::assemble($assemble,UsersModel::getUserInside($conn, $assemble->token));
        $cashback = self::getCashback($conn, $UserExample->caigou);
        if($cashback <= DigitEnum::ZERO){
            Result::success("领取成功,Successfully claimed");
        }
        $手续费比例 = ConfigModel::getConfigSingleValName($conn, Config::PROCURE_FEE);
        $PoolExample = Common::assemble(new PoolExample(),PoolModel::getPoolInside($conn));
        $settlementExample = new SettlementExample();
        $settlementExample->uid = $UserExample->id;
        $settlementExample->type = DigitEnum::THREE;
        $settlementExample->money = $手续费 = $cashback * $手续费比例;
        $奖励 = $cashback - $手续费;
        $手续费池余额 = $PoolExample->user + $手续费;
        $settlementExample->cost = 0;
        $settlementExample->no = $sn = Utils::createOrderNo();
        if($奖励 > DigitEnum::MINIMUM){
            $用户余额 = $UserExample->money + $奖励;
            $conn->shiwuStart();
            $insertSettlementInside = SettlementModel::insertSettlementInside($conn, $settlementExample);
            $SettlementId = $conn->mysql_insert_id();
            $editUserProcureInside = UsersModel::editUserProcureInside($conn, $奖励, $UserExample);
            $writeFundsMoney = Funds::writeFundsMoney($conn, $UserExample->id, $sn, FundsEnum::PURCHASECASHBACK, $奖励, $用户余额, FundsEnum::PURCHASECASHBACKZHCN);
            $upPoolUser = PoolModel::upPoolUser($conn, $手续费, $PoolExample);
            $writeFundsSystem = Funds::writeFundsSystem($conn, $sn, FundsEnum::PURCHASECASHBACK, $手续费, $手续费池余额, FundsEnum::PURCHASECASHBACKZHCN);
            if($insertSettlementInside != DigitEnum::ONE || $editUserProcureInside != DigitEnum::ONE || $writeFundsMoney != DigitEnum::ONE || $upPoolUser != DigitEnum::ONE || $writeFundsSystem != DigitEnum::ONE){
                $conn->shiwuRollback();
                Result::error(ErrorEnum::CLAIMFAILED[$assemble->language]);
            }
            $conn->shiwuEnd();
        }
        if($手续费 >0){
            Sett::settlement($UserExample->id,$SettlementId,$手续费,$sn);
        }
        Result::success("领取成功,Successfully claimed");
    }
    /**
     * 获取用户折扣
     * */
    public static function getDiscount($conn,$capping){
        if($capping >=9999){
            $discount = ConfigModel::getConfigSingleValName($conn,Config::DISCOUNT_9999);
        }else if($capping >=3999){
            $discount = ConfigModel::getConfigSingleValName($conn,Config::DISCOUNT_3999);
        }else if($capping >=999){
            $discount = ConfigModel::getConfigSingleValName($conn,Config::DISCOUNT_999);
        }else if($capping >=99){
            $discount = ConfigModel::getConfigSingleValName($conn,Config::DISCOUNT_99);
        }else{
            $discount = 0;
        }
        return $discount;
    }
    /**
     * 获取用户返现金额
     * */
    public static function getCashback($conn,$caigou){
        if($caigou >=100000){
            $cashback =  ConfigModel::getConfigSingleValName($conn,Config::CASHBACK_10);
        }else if($caigou >=50000){
            $cashback =  ConfigModel::getConfigSingleValName($conn,Config::CASHBACK_5);
        }else if($caigou >=20000){
            $cashback =  ConfigModel::getConfigSingleValName($conn,Config::CASHBACK_2);
        }else if($caigou >=10000){
            $cashback =  ConfigModel::getConfigSingleValName($conn,Config::CASHBACK_1);
        }else{
            $cashback = 0;
        }
        return $caigou * $cashback;
    }
}